#include "jsonrpctcpserver.h"

#include <QTcpServer>
#include <QTcpSocket>
#include <QIODevice>

#include "jsonrpcsocket.h"


JsonRpcTcpServer::JsonRpcTcpServer(){
    p_server = new QTcpServer();
}

JsonRpcTcpServer::~JsonRpcTcpServer(){
    delete p_server;
}

void JsonRpcTcpServer::listen(int port){
    p_server->listen(QHostAddress::Any, port);
    connect(p_server, SIGNAL(newConnection()), this, SLOT(connectClient()));
    qDebug() << "listen";
}

void JsonRpcTcpServer::connectClient(){

    QTcpSocket *clientSocket = p_server->nextPendingConnection();
    QIODevice *device = qobject_cast<QIODevice*>(clientSocket);
    JsonRpcSocket *clientJsonSocket = new JsonRpcSocket(device);

    JsonRpcServer::insertClient(device, clientJsonSocket);

    QObject::connect(clientSocket, SIGNAL(disconnected()), this, SLOT(disconnectClient()));

    Q_EMIT newClient(clientJsonSocket);
    qDebug() << "Client connected";
}

void JsonRpcTcpServer::disconnectClient(){
    QIODevice *sender = static_cast<QIODevice*>(QObject::sender());

    JsonRpcServer::removeClient(sender);
    QObject::disconnect(static_cast<QTcpSocket*>(sender), SIGNAL(disconnected()), this, SLOT(disconnectClient()));
    qDebug() << "Client disconnected";
}



